package org.cypress.rtpack.controller;

import org.cypress.rtpack.VO.SoeIp;
import org.cypress.rtpack.VO.SoePt;
import org.cypress.rtpack.VO.SoeViewData;
import org.cypress.rtpack.common.core.Result;

import org.cypress.rtpack.entity.SoeBiao;
import org.cypress.rtpack.entity.SoeSysname;
import org.cypress.rtpack.service.*;
import org.cypress.rtpack.utils.Dbsvr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author getty
 */
@RestController
@RequestMapping("/soe")
public class SoeController {
    private static final Logger logger = LoggerFactory.getLogger(SoeController.class);


    @Autowired
    private SoeBiaoService soeBiaoService;

    @Autowired
    private ISoeSysnameService soeSysnameService;

    @Autowired
    private ISoeService soeService;

    // 从配置文件注入上传路径
    @Value("${file.upload.dir}")
    private String uploadDir;

    @CrossOrigin
    @GetMapping("/sysname/list")
    public Result<SoeSysname> getSysnameList() {
        List<SoeSysname> list = soeSysnameService.getAll();
        return Result.dataOf(list);
    }

    @CrossOrigin
    @PostMapping("/sysname/create")
    public Result<SoeSysname> SysnameCreate(@RequestBody SoeSysname inst) {
        return soeSysnameService.insertWithCheck(inst);
    }

    @CrossOrigin
    @PutMapping("/sysname/update")
    public Result<SoeSysname> SysnameUpdate(@RequestBody SoeSysname inst) {
        return soeSysnameService.gettyUpdateById(inst);
    }

    @CrossOrigin
    @DeleteMapping("/sysname/deleteById/{id}")
    public Map<String,Object> SysnameDeleteById(@PathVariable int id) {
        soeSysnameService.gettyDeleteById(id);
        Map<String,Object> back = new HashMap<String,Object>();
        back.put("code",0);
        back.put("msg","success");
        return back;
    }

    @CrossOrigin
    @GetMapping("/ip/list/{sysnum}")
    public Result<SoeIp> getIpList(@PathVariable String sysnum) {
        List<SoeIp> list = Dbsvr.getList(String.format("soe_s%spt",sysnum),"soe_ip",SoeIp.class);
        return Result.dataOf(list);
    }

    @CrossOrigin
    @PutMapping("/ip/update/{sysnum}")
    public Result<SoeIp> soeIpUpdate(@PathVariable String sysnum,@RequestBody SoeIp inst) {
        boolean updateRes = Dbsvr.updateEntity(String.format("soe_s%spt",sysnum),"soe_ip","\"index\"",inst);
        SoeIp inst1 = Dbsvr.getEntity(String.format("soe_s%spt",sysnum),"soe_ip",SoeIp.class, inst.getIndex(),"\"index\"");
        return Result.dataOf(inst1);
    }

    @CrossOrigin
    @GetMapping("/pt/list/{sysnum}")
    public Result<SoePt> getPtList(@PathVariable String sysnum) {
        List<SoePt> list = Dbsvr.getList(String.format("soe_s%spt",sysnum),"soe_pt",SoePt.class);
        return Result.dataOf(list);
    }

    @CrossOrigin
    @PutMapping("/pt/update/{sysnum}")
    public Result<SoePt> soePtUpdate(@PathVariable String sysnum,@RequestBody SoePt inst) {
        boolean updateRes = Dbsvr.updateEntity(String.format("soe_s%spt",sysnum),"soe_pt","soe_id",inst);
        SoePt inst1 = Dbsvr.getEntity(String.format("soe_s%spt",sysnum),"soe_pt",SoePt.class, inst.getSoeId(),"soe_id");
        return Result.dataOf(inst1);
    }

    // 文件上传接口
    @CrossOrigin
    @PostMapping("/pt/upload/{sysnum}")
    public Result<SoePt> handlePtFileUpload(@PathVariable String sysnum,@RequestParam("file") MultipartFile file) {
        Map<String,Object> back = new HashMap<>();
        if (file.isEmpty()) {
            return new Result(Result.FAIL_CODE,"上传文件不能为空");
        }
        try {
            // 确保目录存在
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件
            byte[] bytes = file.getBytes();
            Path filePath = Paths.get(uploadDir + file.getOriginalFilename());
            Files.write(filePath, bytes);
            String fileName = filePath.toAbsolutePath().toString();
            List<SoePt> list = PtFileHelper.getPtList(fileName);
            if (list == null || list.isEmpty()) {
                logger.warn("Insert list is empty, nothing to insert");
                return new Result(Result.FAIL_CODE,"文件里没有有效数据");
            }

            // 1. 先清空表
            if (!Dbsvr.dropTable(String.format("soe_s%spt",sysnum), "soe_pt")) {
                logger.error("Failed to drop table before insert");
                return new Result(Result.FAIL_CODE,"清空原数据表出错");
            }
            boolean isSucced = Dbsvr.insertList(String.format("soe_s%spt",sysnum),"soe_pt",list);
            if(isSucced) {
                return Result.dataOf(list);
            }
            else{
                return new Result(Result.FAIL_CODE,"数据写入失败");
            }
        } catch (IOException e) {
            return new Result(Result.FAIL_CODE,"发生错误"+e.getMessage());
        }
    }

    @CrossOrigin
    @GetMapping("/view_data/list/{sysnum}")
    public Result<SoeViewData> getViewDataList(@PathVariable String sysnum) {
        List<SoeViewData> list = soeService.getSoeViewList(sysnum);
        return Result.dataOf(list);
    }

    @CrossOrigin
    @GetMapping("/description/bytag/{sysnum}/{tagName}")
    Result<SoeBiao> getSoeByname(@PathVariable String sysnum,@PathVariable String tagName)
    {
        SoeBiao inst1 = Dbsvr.getEntity(String.format("soe_s%spt",sysnum),"soe_biao",SoeBiao.class, tagName,"tag_name");
        return Result.dataOf(inst1);
    }

    @CrossOrigin
    @GetMapping("/description/list/{sysnum}")
    public Result<SoeBiao> gettagnameList(@PathVariable String sysnum)
    {
        List<SoeBiao> list = Dbsvr.getList(String.format("soe_s%spt",sysnum),"soe_biao",SoeBiao.class);
        return Result.dataOf(list);
    }
}
